<template>
  <div class="personal-container">
    <!-- 头部导航 -->
    <el-header class="header">
          <h1 style="text-align: center">个人中心</h1>
    </el-header>

    <!-- 主体内容 -->
    <el-main class="main-content">
      <el-row :gutter="30">
        <!-- 左侧头像区 -->
        <el-col :xs="24" :sm="8" :md="6">
          <div class="avatar-section">
            <el-avatar
                :size="150"
                :src="data.avatarUrl || img"
            />
            <h2 class="username">{{ data.userName || '未设置用户名' }}</h2>
              <el-button type="primary" class="edit-btn" @click="showEditDialog">
                编辑资料
              </el-button>
              <el-button type="danger" class="edit-btn" @click="showEditDialog1">
                修改密码
              </el-button>
          </div>
        </el-col>

        <!-- 右侧信息区 -->
        <el-col :xs="24" :sm="16" :md="18">
          <el-descriptions title="基本信息" border column="1">
            <el-descriptions-item label="性别">
              {{ data.sex }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ data.phone || '未设置电话' }}
            </el-descriptions-item>
            <el-descriptions-item label="个性签名">
              {{ data.likeself|| '这个人很懒，什么都没留下～' }}
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">
              {{ formatDate(data.createdTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-main>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑资料" width="30%" class="el-dialog">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="data.userName" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="data.phone" />
        </el-form-item>
        <el-form-item label="个性签名">
          <el-input v-model="data.likeself" type="textarea" maxlength="50"
                    :placeholder = hh
                    show-word-limit
                    />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="initData" >取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改密码" width="30%" v-model="dialogVisible1" class="el-dialog">
      <el-form ref="formRef" :rules="newdata.rules" label-width="100px" :model="newdata.form">
        <el-form-item label="原密码" prop="password">
          <el-input v-model="newdata.form.password"/>
        </el-form-item>
        <el-form-item label="请输入新密码" prop="newpassword">
          <el-input  prefix-icon="Lock" v-model="newdata.form.newpassword"/>
        </el-form-item>
        <el-form-item label="再次确认密码" prop="againpassword">
          <el-input   v-model="newdata.form.againpassword"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="initData1" >取消</el-button>
        <el-button type="primary" @click="updatepassword">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import { reactive, ref ,computed} from "vue";
import { ElMessage } from "element-plus";
import img from '@/assets/background.bmp';
import request from "@/utils/request.js";

const dialogVisible = ref(false);
const dialogVisible1 = ref(false);

const formRef = ref ();

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次确认密码'))
  } else if (value !== newdata.form.newpassword) {
    callback(new Error("两次密码不一致"))
  } else {
    callback()
  }
}

//用户数据
const data = reactive({
  userId:'',
  password:'',
  userName: '',
  phone: '',
  avatarUrl: '',
  createdTime:'',
  newpassword:'',
  likeself: '',
  sex:'',
  form:{},
});

const newdata = reactive({
  userId:'',
  password:'',
  userName: '',
  phone: '',
  avatarUrl: '',
  createdTime:'',
  likeself: '',
  sex:'',
  newpassword:'',
  againpassword:'',
  form: {},
  rules: {
    password: [
      { required: true, message: '请输入原密码', trigger: 'blur'}
    ],
    newpassword: [
      { required: true, message: '请输入新密码', trigger: 'blur'}
    ],
    againpassword: [
      { validator: validatePass , trigger: 'blur'}
    ]
  },
})



// 初始化用户数据
const initData = () => {
  const userData = JSON.parse(localStorage.getItem('car-home-user')) || {};
  Object.assign(data,userData);
  dialogVisible.value = false;
};

const initData1 = () => {
  dialogVisible1.value = false;
};

//小创意
const hh =  computed(() => "发挥想象力吧！！"+ data.userName + "酱")

// 转换时间格式
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

//编辑资料框的是否
const showEditDialog = () => {
  dialogVisible.value = true;
};

const showEditDialog1 = () => {
  dialogVisible1.value = true;
};

//保存资料
const saveProfile = () => {
  data.newpassword = data.password
  request.put('/Home/person',data).then(res =>{
    if(res.code === '200'){
      console.log(data)
      localStorage.setItem('car-home-user',JSON.stringify(data))
      ElMessage.success('操作成功')
    }else{
      ElMessage.error(res.msg)
      initData()
    }
  })
  ElMessage.success('资料保存成功');
  dialogVisible.value = false;
};

const updatepassword = () => {
  console.log(newdata)
  formRef.value.validate((valid) => {
    if (valid) {
      if(data.password === newdata.form.password){
        if(data.form.newpassword !== data.password){
          newdata.form.userName = data.userName;
          newdata.form.userId = data.userId;
          newdata.form.likeself = data.likeself;
          newdata.form.phone = data.phone;
          newdata.form.sex = data.sex;
          newdata.form.avatarUrl = data.avatarUrl;
          newdata.form.createdTime = data.createdTime;
          request.put('/Home/person',newdata.form).then(res =>{
            console.log(newdata.form)
            console.log(res.data)
            if(res.code === '200'){
              localStorage.setItem('car-home-user',JSON.stringify(newdata.form))
              initData();
              dialogVisible1.value = false;
              ElMessage.success('操作成功')
            }else{
              ElMessage.error(res.msg)
            }
          })
        }else{
          ElMessage.error('新密码不能与原密码相同')
        }
      }

      else{
        ElMessage.error('原密码错误');
      }
    } else {
    }
  })
};

// 初始化
initData();
</script>

<style scoped>
.personal-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.avatar-section {
  text-align: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.username {
  margin: 15px 0;
  color: #333;
}

.edit-btn {
  margin-top: 15px;
  width: 40%;
}

.main-content {
  margin-top: 30px;
}

</style>